package com.tongshu.miaosha.service;

import com.tongshu.miaosha.dao.MiaoshaUserDao;
import com.tongshu.miaosha.domain.MiaoshaUser;
import com.tongshu.miaosha.exception.GlobalException;
import com.tongshu.miaosha.redis.MiaoshaUserKey;
import com.tongshu.miaosha.result.CodeMsg;
import com.tongshu.miaosha.utils.MD5Util;
import com.tongshu.miaosha.utils.RedisUtil;
import com.tongshu.miaosha.utils.UUIDUtil;
import com.tongshu.miaosha.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.CoderMalfunctionError;
import java.time.Duration;

@Service
public class MiaoshaUserService {
    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    private MiaoshaUserDao miaoshaUserDao;
    @Autowired
    private RedisUtil redisUtil;

    public MiaoshaUser getById(long id) {
        // 取缓存
        MiaoshaUser user = (MiaoshaUser)redisUtil.get(MiaoshaUserKey.getById, "" + id);
        if (user != null)
            return user;
        // 取数据库
        user = miaoshaUserDao.selectById(id);
        if (user != null)
            redisUtil.set(MiaoshaUserKey.getById, ""+id, user);
        return user;
    }

    // 更新秒杀用户密码
    public boolean updatePassword(String token, long id, String formPass) {
        // 取user
        MiaoshaUser user = getById(id);
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        // 更新数据库
        MiaoshaUser toBeUpdate = new MiaoshaUser();
        toBeUpdate.setId(id);
        toBeUpdate.setPassword(MD5Util.formPassToDBPass(formPass, user.getSalt()));
        miaoshaUserDao.updateById(toBeUpdate);
        // 处理缓存
        redisUtil.del(MiaoshaUserKey.getById, ""+id);
        user.setPassword(toBeUpdate.getPassword());
        redisUtil.set(MiaoshaUserKey.token, token, user);
        redisUtil.set(MiaoshaUserKey.getById, ""+id, user);
        return true;
    }

    public boolean login(HttpServletResponse response, LoginVo loginVo) {
        if (loginVo == null) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVo.getMobile();
        String formpass = loginVo.getPassword();
        // 判断手机号是否存在
        MiaoshaUser user = getById(Long.parseLong(mobile));
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        // 验证密码
        String dbPass = user.getPassword();
        String saltDB = user.getSalt();
        String calcPass = MD5Util.formPassToDBPass(formpass, saltDB);
        if(!calcPass.equals(dbPass)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        String token = UUIDUtil.uuid();
        // 生成token
        addCookie(response,token, user);
        return true;
    }

    public MiaoshaUser getByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token))
            return null;
        MiaoshaUser miaoshaUser = (MiaoshaUser) redisUtil.get(MiaoshaUserKey.token, token);
        if (miaoshaUser != null)
            addCookie(response,token, miaoshaUser); // 延迟Cookie有效期
        return miaoshaUser;
    }

    private void addCookie(HttpServletResponse response,String token, MiaoshaUser user) {
        redisUtil.set(MiaoshaUserKey.token, token, user);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
